<script setup lang="ts">
import { ref, reactive, defineEmits, defineProps, watch, onMounted } from "vue";
import { ElMessage, ElForm } from "element-plus";
import { updateAlertPeopleApi, AlertPeopleModel } from '@/api/alerts/alertPeople';
import { useI18n } from 'vue-i18n';
import { useLogic } from "@/views/system/user/logic/logic";

const props = defineProps<{
  visible: boolean;
  people: AlertPeopleModel | null;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'success': [];
}>();

const { t } = useI18n();
const {deptTreeList, getDeptTree} = useLogic();

onMounted(async () => {
  await getDeptTree();
});

// 表单数据
const formData = reactive<Partial<AlertPeopleModel>>({
  name: '',
  deptId: 0,
  phone: '',
  email: '',
  language: 'cn',
  wechat: '',
  remark: '',
  receiveFrequency: 0,
  status: 1
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: t('alerts.peoplePage.table.name') + ' ' + t('buttons.required'), trigger: 'blur' }
  ],
  email: [
    { required: true, message: t('alerts.peoplePage.table.email') + ' ' + t('buttons.required'), trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  deptId: [
    { required: true, message: t('alerts.peoplePage.table.deptId') + ' ' + t('buttons.required'), trigger: 'change' }
  ],
  phone: [
    { required: true, message: t('alerts.peoplePage.table.phone') + ' ' + t('buttons.required'), trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
};

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();

// 监听联系人数据变化，更新表单
watch(() => props.people, (newPeople) => {
  if (newPeople) {
    // 深拷贝联系人数据到表单
    Object.assign(formData, { ...newPeople });
  }
}, { immediate: true, deep: true });

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false);
};

// 保存数据
const handleSave = async () => {
  if (!formRef.value || !props.people) return;

  try {
    await formRef.value.validate();

    const response = await updateAlertPeopleApi(props.people.id, formData);
    if (response.code === 0) {
      ElMessage.success(t('alerts.peoplePage.updateSuccess'));
      emit('success');
      handleClose();
    } else {
      ElMessage.error(response.msg || t('alerts.peoplePage.updateFailed'));
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(t('alerts.peoplePage.updateFailed'));
    }
  }
};

// 语言选项
const languageOptions = [
  { label: '中文', value: 'cn' },
  { label: 'English', value: 'en' }
];
</script>

<template>
  <el-dialog
    v-model="props.visible"
    :title="t('buttons.edit')"
    width="600px"
    @close="handleClose"
    draggable
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
    >
      <el-form-item :label="t('alerts.peoplePage.table.name')" prop="name">
        <el-input v-model="formData.name" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.deptId')" prop="deptId">
        <el-cascader
          v-model="formData.deptId"
          class="w-full"
          :options="deptTreeList"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('alerts.peoplePage.table.deptId')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.phone')" prop="phone">
        <el-input v-model="formData.phone" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.email')" prop="email">
        <el-input v-model="formData.email" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.language')">
        <el-select v-model="formData.language" placeholder="">
          <el-option
            v-for="option in languageOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.receiveFrequency')">
        <el-input-number v-model="formData.receiveFrequency" :min="1" :precision="0" :step="1" />
        <span class="ml-2 text-sm text-gray-500">{{t('time.min')}}</span>
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.wechat')">
        <el-input v-model="formData.wechat" placeholder="" />
      </el-form-item>
      <el-form-item :label="t('alerts.peoplePage.table.remark')">
        <el-input v-model="formData.remark" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ t('buttons.cancel') }}</el-button>
        <el-button type="primary" @click="handleSave">{{ t('buttons.save') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
